package com.china08.yxyapi.api.comm.upload;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.util.YXCSPUtil;

@CrossOrigin
@RestController("UploadSliderForAppController")
public class UploadSliderForAppController {

    @Autowired
    private YXCSPUtil yxcspUtil;

    /**
     * 上传文件
     * 
     * @throws IOException
     */
    @RequestMapping(value = "/api_yw/comm/upload/sliderforapp", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel upLoadWenDoc(@RequestParam(value = "file", required = false) MultipartFile file)
            throws IOException {
        RespModel respModel = new RespModel();
        try {
            Assert.isTrue(file.getSize() != 0, "文件不能为空!");
            Assert.isTrue(file.getSize() < 2 * 1024 * 1024, "文件不能大于2mb!");

            String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
            boolean b1 = fileExt.equalsIgnoreCase("gif");
            boolean b2 = fileExt.equalsIgnoreCase("png");
            boolean b3 = fileExt.equalsIgnoreCase("jpeg");
            boolean b4 = fileExt.equalsIgnoreCase("jpg");
            Assert.isTrue((b1 || b2 || b3 || b4), "请选择gif、png、jpg、jpeg类型文件上传");

            BufferedImage bi = ImageIO.read(file.getInputStream());
            Integer width = bi.getWidth();
            Integer height = bi.getHeight();

            String tishixinxi = "为了您的页面美观,您上传的图片格式必须为：宽度726-746像素之间,高度270-290像素之间,请您制作好以后在进行上传。";
            Assert.isTrue((width >= 726 && width <= 746), tishixinxi);
            Assert.isTrue((height >= 270 && height <= 290), tishixinxi);

            String url = yxcspUtil.push(file);
            respModel.url = url;
            respModel.msg = "上传成功";
        } catch (Exception e) {
            respModel.success = false;
            respModel.msg = e.getMessage();
        }
        return respModel;
    }

    protected static class RespModel extends YxyApiRespModel {
        public boolean success = true;
        public String url;
        public String msg;
    }
}
